package com.product.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Map;

/**
 * 向模型发送请求
 */
@Component
public class DetectionService {

    @Value("${model.service.url}")
    private String modelServiceUrl;

    @Autowired
    private RestTemplate restTemplate;

    public String detectionFile(String file) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", file);

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        ResponseEntity<Map> response = restTemplate.postForEntity(modelServiceUrl + "/predictByStr", requestEntity, Map.class);
        System.out.println(response.getBody().get("url"));
        Map<String, String> data = response.getBody();
        if (data.get("predict").equals("true")) {
            return null;
        }
        return data.get("url");
    }
}
